package com.joyveb.webtest.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.Data;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

import com.joyveb.lbos.restful.common.WebRestException;
import com.joyveb.lbos.restful.spring.ChecksumRequestBody;

@Controller
@RequestMapping(value = "/hello")
public class HelloController {

	@ResponseBody
	@RequestMapping(method = RequestMethod.GET)
	public String hello(HttpServletRequest request, HttpServletResponse response) {
		try {
			response.setHeader("headerResponse", URLEncoder.encode("{\"helloResult\":1,\"desc\":\"操作成功\"}", "UTF-8"));
			response.setHeader("Authorization", "Bearer t12098j");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "hello";
	}

	@RequestMapping(method = RequestMethod.GET, value = "/error")
	public String errorGet(@RequestParam String type) {
		if ("1".equals(type)) {
			throw new WebRestException("WebRestException错误.");
		} else if ("2".equals(type)) {
			try {
				throw new RuntimeException("RuntimeException错误.");
			} catch (Exception e) {
				throw new WebRestException(e);
			}
		}
		return "success";
	}

	@RequestMapping(method = RequestMethod.POST, value = "/error1")
	@ResponseBody
	@ResponseStatus(value = HttpStatus.OK)
	public void error1Post(@ChecksumRequestBody String type) {
		// return "success";
	}

	@RequestMapping(method = RequestMethod.POST, produces = "application/json", value = "/post")
	@ResponseBody
	public String errorPost(@ChecksumRequestBody TestBean type) {
		System.out.println(type);
		return "success";
	}

//	@RequestMapping(value = "/**", method = RequestMethod.GET)
//	public void handleCall(HttpServletRequest request) {
//		String url = request.getRequestURI();
//		System.out.println(url);
//		throw new RuntimeException("");
//	}

	public @Data static class TestBean {
		private String name;
		private int age;
	}
}
